home *** CD-ROM | disk | FTP | other *** search
/ Power Programmierung / Power-Programmierung (Tewi)(1994).iso / magazine / c_news / 17 / dice.msc < prev    next >
Text File  |  1989-09-01  |  2KB  |  53 lines

  1. /*  DICE.C -- A program to simulate dice rolling.  The program rolls
  2.     the number of dice specified by the user on the command line.
  3.  
  4.     This program is part of an article illustrating command-line
  5.     parameters in issue 17 of the C News.  */
  6.  
  7. #include <stdlib.h>
  8. #include <stdio.h>
  9. #include <time.h>
  10.  
  11. void main(int argc, char *argv[])  /*  Pass the number of dice to be rolled
  12.                        when calling the program.  The number
  13.                        will be passed as argv[1]. (argv[0]
  14.                        is the program name.)  */
  15. {
  16.     int roll, dice, count = 0;  /*  Initialize variables for each roll
  17.                     (roll),    the number of dice (dice),
  18.                     and a counter (count) which is set
  19.                     to 0.  */
  20.  
  21.     if(argc == 1)   /*  If no parameter for the number of dice was
  22.                 passed when calling the program, print instruc-
  23.                 tions for use and terminate program.  */
  24.     {
  25.         puts("\nProper format is:");
  26.         puts("\n                  dice n");
  27.         puts("\nand n is an integer representing the number of ");
  28.         puts("dice to be rolled.\n");
  29.         exit(0);
  30.     }
  31.  
  32.     dice = atoi(argv[1]);  /*  Convert the string value for the number,
  33.                    passed from the command-line as argv[1],
  34.                    of dice to an integer value.  */
  35.  
  36.  
  37.     srand((unsigned)time(NULL));  /*  Initialize the random number generator with a
  38.               random number.  */
  39.  
  40.     while(count < dice)  /*  Using the number of dice, generate a
  41.                  random number for each "roll" of the
  42.                  dice and display the value to the
  43.                  screen.  When the variable count equals
  44.                  the number of dice requested, the loop
  45.                  terminates (as does the program).  */
  46.     {
  47.         roll = (rand()%6);    /*  Use standard six-sided dice.  */
  48.         printf("The roll of dice number %d is %d", count+1, ++roll);
  49.         printf("\n");
  50.         count++;
  51.     }
  52. }
  53.